package com.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.util.ControllerManager;
import com.util.PathUtil;
import com.util.StringUtil;
import javafx.application.Platform;
import javafx.concurrent.Worker;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import lombok.Getter;
import netscape.javascript.JSObject;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author Ricky
 * @date 2020-8-12 16:47
 */
public class WebViewController implements Initializable {

    @FXML
    AnchorPane root;

    @FXML
    WebView webView;

    WebEngine engine;

    @Getter
    String fxmlName;

    private WebViewController secondaryController;
    private WebViewController primaryController;

    public WebViewController(String fxmlName) {
        this.fxmlName = fxmlName;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        primaryController = ControllerManager.getControllerByFxmlName("primary");
        secondaryController = ControllerManager.getControllerByFxmlName("secondary");

        engine = webView.getEngine();
//        URL url = PathUtil.getURL("html/" + this.fxmlName + ".html");
        String url = "http://localhost:8080/" + this.fxmlName + ".html";
        engine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> {
            if (newState == Worker.State.SUCCEEDED) {
                JSObject win = (JSObject) engine.executeScript("window");
                win.setMember("java", this);
            }
        });
        engine.load(url.toString());
    }

    Stage getStage() {
        return (Stage) root.getScene().getWindow();
    }

    public void showStage() {
        getStage().show();
    }

    public void hideStage() {
        getStage().hide();
    }

    public void closeStage() {
        getStage().close();
    }

    public void sendMsg(String msg) {
        if ("primary".equals(this.fxmlName)) {
            secondaryController.receiveMsg(msg);
        } else if ("secondary".equals(this.fxmlName)) {
            primaryController.receiveMsg(msg);
        }
    }

    public void receiveMsg(String msg) {
        engine.executeScript("receiveMsg(" + msg + ")");
    }

    public void sendEvt(String msg) {
        if ("primary".equals(this.fxmlName)) {
            secondaryController.receiveEvt(msg);
        } else if ("secondary".equals(this.fxmlName)) {
            primaryController.receiveEvt(msg);
        }
    }

    public void receiveEvt(String msg) {
        engine.executeScript("receiveEvt(" + msg + ")");
    }


    public List<String> showOpenDialog(String param) throws IOException {
        JSONObject jsonObject = JSONObject.parseObject(param);
        if (jsonObject == null) {
            jsonObject = new JSONObject();
        }

        List<String> stringList = new ArrayList<>();

        // 选择文件
        Boolean openFile = jsonObject.getBoolean("openFile");
        if (openFile == null) {
            openFile = true;
        }
        // 选择文件夹
        Boolean openDirectory = jsonObject.getBoolean("openDirectory");
        if (openDirectory == null) {
            openDirectory = false;
        } else if (openDirectory) {
            openFile = false;
        }
        // 多选
        Boolean multiSelections = jsonObject.getBoolean("multiSelections");
        if (multiSelections == null) {
            multiSelections = false;
        }
        // 显示隐藏文件
        Boolean showHiddenFiles = jsonObject.getBoolean("showHiddenFiles");
        if (showHiddenFiles == null) {
            showHiddenFiles = false;
        }

        String title = jsonObject.getString("title");
        if (StringUtil.isEmpty(title)) {
            title = "选择文件";
        }

        String defaultPath = jsonObject.getString("defaultPath");
        if (StringUtil.isEmpty(defaultPath)) {
            defaultPath = System.getProperty("user.home");
        }
        File initialDirectory = new File(defaultPath);

        if (openFile) {
            FileChooser fileChooser = new FileChooser();

            // 设置标题
            fileChooser.setTitle(title);

            // 设置默认路径
            fileChooser.setInitialDirectory(initialDirectory);

            // 过滤器
            JSONArray jsonArray = jsonObject.getJSONArray("filters");
            List<FileChooser.ExtensionFilter> filters = new ArrayList<>();
            if (jsonArray != null) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject item = jsonArray.getJSONObject(i);
                    JSONArray extensions = item.getJSONArray("extensions");
                    String name = item.getString("name");
                    List<String> exts = new ArrayList<>();
                    for (int i1 = 0; i1 < extensions.size(); i1++) {
                        exts.add("*." + extensions.getString(i1));
                    }
                    filters.add(new FileChooser.ExtensionFilter(name, exts));
                }
            }
            fileChooser.getExtensionFilters().addAll(filters);


            if (multiSelections) {
                List<File> fileList = fileChooser.showOpenMultipleDialog(getStage());
                if (fileList == null) {
                    return null;
                }
                for (File file : fileList) {
                    stringList.add(file.getCanonicalPath());
                }
            } else {
                File file = fileChooser.showOpenDialog(getStage());
                if (file == null) {
                    return null;
                }
                stringList.add(file.getCanonicalPath());
            }
        } else if (openDirectory) {

            DirectoryChooser directoryChooser = new DirectoryChooser();
            directoryChooser.setTitle(title);
            directoryChooser.setInitialDirectory(initialDirectory);
            File file = directoryChooser.showDialog(getStage());
            if (file == null) {
                return null;
            }
            stringList.add(file.getCanonicalPath());
        }
        return stringList;
    }

    public JSONObject getLocation() {
        Stage stage = getStage();
        double x = stage.getX();
        double y = stage.getY();
        return new JSONObject() {{
            put("x", x);
            put("y", y);
        }};
    }

    public void setLocation(int x, int y) {
        Stage stage = getStage();
        stage.setX(x);
        stage.setY(y);
    }

    public JSONObject getMouseLocation() {
        Point location = MouseInfo.getPointerInfo().getLocation();
        return new JSONObject() {{
            put("x", location.x);
            put("y", location.y);
        }};
    }

    public void exitProgram() {
        Platform.exit();
    }

    public void maximixed(boolean isMax) {
        Stage stage = getStage();
        stage.setMaximized(isMax);
    }

    public void minimixed() {
        Stage stage = getStage();
        stage.setIconified(true);
    }

}
